package com.zhangmeng.online.exam.ui.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.components.DynamicTableComponent;
import com.zhangmeng.online.exam.ui.module.SubjectType;
import com.zhangmeng.online.exam.ui.service.SubjectService;
import com.zhangmeng.online.exam.ui.service.UserService;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import com.zhangmeng.online.exam.ui.utils.FxUtils;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;

import java.util.HashMap;
import java.util.Map;

import static com.zhangmeng.online.exam.ui.utils.FxUtils.FX_BEANS;

/**
 * @author zm
 * @date 2025/4/6 14:58
 * @version: 1.0
 */
public class PaperEditController {

    @FXML
    public TextField nameField;

    @FXML
    public TextArea descriptionTextArea;

    @FXML
    public TextField scoreField;

    @FXML
    public TextField passScoreField;

    @FXML
    public TextField examTimeField;

    @FXML
    public ComboBox<Status> statusComboBox;

    @FXML
    public ComboBox<SubjectType> subjectBox;

    @FXML
    public void initialize() {
        // 初始化状态下拉框
        Status status1 = new Status("启用", 1);
        Status status2 = new Status("禁用", 0);
        statusComboBox.getItems().addAll(status1, status2);
        statusComboBox.setValue(status1);

        statusComboBox.setConverter(new StringConverter<Status>() {
            @Override
            public String toString(Status object) {
                return object.getName();
            }

            @Override
            public Status fromString(String string) {
                return null;
            }
        });

        statusComboBox.setCellFactory(new Callback<ListView<Status>, ListCell<Status>>() {
            @Override
            public ListCell<Status> call(ListView<Status> statusListView) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(Status item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null && !empty) {
                            HBox hBox = new HBox();
                            Label label = new Label(item.getName());
                            hBox.getChildren().add(label);
                            setGraphic(hBox);
                        }
                    }
                };
            }
        });

        subjectBox.getItems().addAll(SubjectService.getALLSubjectType());
        subjectBox.getSelectionModel().selectFirst();
        subjectBox.setConverter(new StringConverter<SubjectType>() {
            @Override
            public String toString(SubjectType object) {
                return object.getName();
            }

            @Override
            public SubjectType fromString(String string) {
                return null;
            }
        });
    }

    @FXML
    public void handleSave(ActionEvent actionEvent) {

        // 保存试卷信息
        if (nameField.getText().trim().isEmpty()) {
            AlertUtils.alert_warning("试卷名称不能为空！");
            return;
        }

        if (descriptionTextArea.getText().trim().isEmpty()) {
            AlertUtils.alert_warning("试卷描述不能为空！");
            return;
        }

        if (scoreField.getText().trim().isEmpty()) {
            AlertUtils.alert_warning("总分不能为空！");
            return;
        }

        if (passScoreField.getText().trim().isEmpty()) {
            AlertUtils.alert_warning("及格分数不能为空！");
            return;
        }

        if (examTimeField.getText().trim().isEmpty()) {
            AlertUtils.alert_warning("考试时间不能为空！");
            return;
        }
        // 保存试卷信息
        Map<String, Object> params = new HashMap<>();
        params.put("token", UserService.getCurrentUser().getToken());
        params.put("name", nameField.getText().trim());
        params.put("description", descriptionTextArea.getText().trim());
        params.put("score", scoreField.getText().trim());
        params.put("passScore", passScoreField.getText().trim());
        params.put("examTime", examTimeField.getText().trim());
        params.put("status", statusComboBox.getValue().getValue());
        params.put("subjectId", subjectBox.getSelectionModel().getSelectedItem().getId());

        String response = HttpUtils.POST(ApiUtils.API_URL + "/paper/save", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("code") == 200) {
            Alert alert = AlertUtils.alert_msg("保存成功！");
            handleCancel();
        } else {
            AlertUtils.alert_warning("保存失败！" + jsonObject.getString("msg"));
        }
    }

    @FXML
    public void handleCancel() {

        Stage window = (Stage) subjectBox.getScene().getWindow();
        window.close();
        //刷新数据
        DynamicTableComponent dynamicTableComponent = FX_BEANS.get(FxUtils.Paper_DynamicTableComponent);
        dynamicTableComponent.flushData();

    }

    public static class Status {
        private String name;
        private int value;

        public Status(String name, int value) {
            this.name = name;
            this.value = value;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }
}
